from sys import argv
from subprocess import check_output, CalledProcessError
from my_utils import Timer, alertor


class Shell(Timer):
    def __init__(self, **kwargs):
        super().__init__()
        self.parameters = kwargs
        # 从命令行获取参数
        for a in argv[1:]:
            k, v = a.split('=', 1)
            self.parameters[k.strip()] = v.strip()

    def sh_cmd(self, cmd):
        """执行Linux命令并返回结果，Python2返回str，Python3返回bytes"""
        if self.system == 'Linux':
            return check_output(cmd, shell=True).decode().strip()
        return cmd

    def sh_cmd_and_alert(self, cmd):
        """执行Linux命令并返回结果，执行失败将会发送到企业微信"""
        if self.system == 'Linux':
            try:
                return check_output(cmd, shell=True).decode().strip()
            except CalledProcessError as e:
                alertor.alert(cmd, e)
        return cmd

    def get(self, key, default):
        """获取参数值"""
        return self.parameters.get(key, default)

    def __getitem__(self, item):
        return self.parameters[item]

    @property
    def ymd(self):
        """获取日期，格式YYYY-MM-DD，默认昨天"""
        return self.get('ymd', self.yesterday)


if __name__ == '__main__':
    _sh = Shell(abc='ABC')
    print(_sh['abc'], _sh.ymd)
